from apps.merchant.shopCart.baseViews import *
from django.db.models import Sum

def getShopCarts(self):
    return ShopCartDao().findAll().filter(item__status = 1, item__checkStatus='PASS', sku__status = 1, sku__stock__gt = 0, sku__is_delete = 0)

class ShopCartViewSet(BaseShopCartViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = getShopCarts(self).select_related('item', 'sku')
        return _list

    @action(methods=['post'], detail=False)
    def jsonShopCart(self, request):
        params = getRequestParams(self.request)
        scene = params.get('scene')
        if isEmptyStr(scene):
            return Response(response_error('scene不能为空'))
        params['user'] = request.user.id
        _shopCarts =  getShopCarts(self).filter(scene=scene, user=request.user.id, item=params.get('item'), specValues=params.get('specValues'))
        if _shopCarts.exists():
            shopCart = _shopCarts.first()
            shopCart.payCount = F('payCount') + params.get('payCount')
            shopCart.save()
        else:
            ShopCartDao().create(params)        
        return Response(response_success('已加入购物车'))
    
    @action(methods=['post'], detail=False)
    def shopCartCountChange(self, request):
        params = getRequestParams(self.request)
        _obj_id = params.get('obj_id')
        if not _obj_id:
            return Response(response_error('obj_id不能为空'))
        ShopCartDao().update(_obj_id, {'payCount': params.get('payCount')})
        return Response(response_success('操作成功'))
    
    @action(methods=['post'], detail=False)
    def getShopCartCount(self, request):
        params = getRequestParams(self.request)
        scene = params.get('scene')
        if isEmptyStr(scene):
            return Response(response_error('scene不能为空'))
        payCount = getShopCarts(self).filter(scene=scene, user=request.user).aggregate(sums=Sum('payCount'))['sums'] or 0

        return Response(response_success({'count': payCount}))